import os
import json

from pydantic import BaseModel


def dump_obj_to_json(obj: BaseModel, json_path):

    with open(json_path, "w") as f:
        json.dump(obj.model_dump(), f, ensure_ascii=False, indent=4)

def load_obj_from_json(json_path, obj_cls: BaseModel):

    with open(json_path, "r") as f:
        obj_dict = json.load(f)
    return obj_cls(**obj_dict)

def dump_list_obj(list_obj: list[BaseModel], json_path, refresh=False):
    if refresh and os.path.exists(json_path):
        for file in os.listdir(json_path):
            os.remove(os.path.join(json_path, file))
    if not os.path.exists(json_path):
        os.makedirs(json_path)
    index = 0
    for i in list_obj:
        if not isinstance(i, BaseModel):
            raise ValueError(f"Object {i} is not a BaseModel object.")
        save_name = os.path.join(json_path, f"{index}.json")
        dump_obj_to_json(i, save_name)
        index += 1

def load_list_obj(json_path, obj_cls: BaseModel):
    list_obj = []
    for file in os.listdir(json_path):
        if file.endswith(".json"):
            file_path = os.path.join(json_path, file)
            list_obj.append(load_obj_from_json(file_path, obj_cls))
    return list_obj